package com.czy.utilslib.permission;


import android.app.Activity;
import android.content.pm.PackageManager;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.czy.utilslib.debug.DebugUtil;
import com.permissionx.guolindev.PermissionX;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PermissionUtil {

    private static final String TAG = PermissionUtil.class.getSimpleName();

    public static void initPermission(FragmentActivity activity, String[] permissions){
        PermissionX.init(activity)
                .permissions(permissions)
                .request((allGranted, grantedList, deniedList) -> {
                    if(allGranted){
                        activity.runOnUiThread(() -> Toast.makeText(activity, "已授权", Toast.LENGTH_SHORT).show());
                    }
                    else {
                        activity.runOnUiThread(() -> Toast.makeText(activity, "未授权", Toast.LENGTH_SHORT).show());
                        DebugUtil.logR("grantedList:" + Arrays.toString(grantedList.toArray()));
                        DebugUtil.logR("deniedList:" + Arrays.toString(deniedList.toArray()));
                    }
                });
    }

    public static void requestPermissionsX(FragmentActivity activity, String[] permissions, GainPermissionCallback callback){
        PermissionX.init(activity)
                .permissions(permissions)
                .request((allGranted, grantedList, deniedList) -> {
                    if(allGranted){
                        DebugUtil.logI(TAG, TAG + ":全部授权");
                        callback.callback();
                    }
                    else {
                        DebugUtil.logI(TAG, TAG + ":未授权：");
                        DebugUtil.logI(TAG,"grantedList:" + Arrays.toString(grantedList.toArray()));
                        DebugUtil.logI(TAG,"deniedList:" + Arrays.toString(deniedList.toArray()));
                    }
                });
    }

    public static void requestPermissions(Activity activity, String[] permissions, int requestCode) {
        List<String> permissionList = new ArrayList<>();

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            String[] permissionsArray = permissionList.toArray(new String[0]);
            ActivityCompat.requestPermissions(activity, permissionsArray, requestCode);
        }
    }

}
